
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/msg.h>
 
#define MSG_NAME "./msg_file"
 
/*struct msgbuf
{
    long mtype;
    char mtext[1024];
};*/
 
int main(int argc, char const *argv[])
{
    key_t key;
    int msgid;
 
    key = ftok(MSG_NAME, 'k');
 
    if (msgid = msgget(key, 0655 | IPC_CREAT) < 0)
    {
        perror("msgid error");
    }
 
    printf("key = %x\n", key); // key 值相同生成的消息队列也相同
    printf("msgid = %d\n", msgid);
 
    char buffer[1024];
    long mtype;
    struct msgbuf pmsgbuf;
 
    while (1)
    {
        memset(buffer, 0, sizeof(buffer));
        memset(&pmsgbuf, 0, sizeof(struct msgbuf));
        printf("Please input send msg:\n");
        scanf("%s", buffer);
        strcpy(pmsgbuf.mtext, buffer);
        printf("Please input send id\n");
        scanf("%ld", &mtype);
        pmsgbuf.mtype = mtype;
 
        if (msgsnd(msgid, (void *)&pmsgbuf, sizeof(pmsgbuf), IPC_NOWAIT) < 0)
        {
            perror("msg snd error");
        }
    }
 
    return 0;
}
